<%@ include file="../include.jsp" %>
<jsp:include page="../dynamic_grid.jsp"/>
<%@ include file="../include_ajax.jsp" %>


<head>
    <title>Zonas - Gestión Zonas</title>
</head>

<h1>Gestion de Zonas</h1>

<head>

<%-- <style type="text/css">
    v\:* {
        behavior: url(#default#VML);
    }

    body {
        font-family: Arial, Helvetica, Sans Serif;
        font-size: 10pt;
    }
</style--%>
<script type="text/javascript"
        src="<c:url value='http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAku8DcWMwO9f8YVy4Qbom3RSmOB7sRPneGnHdBjmMnq4YTUhpZxQLtjgcKvFYOImH-uVUqU8bi4sEOQ'/>"></script>
<script type="text/javascript" src="<c:url value='/dwr/interface/managerHelper.js'/>"></script>


<script type="text/javascript">


var map;
var globoCoordenadas;
var totalLat = 0;
var totalLon = 0;
var polyShape;
var polygonMode;
var polygonDepth = "20";
var polyPoints = Array();
var drawMode;
var oldMarker;
var geocoder = null;

var fillColor = "#0000FF"; // blue fill
var lineColor = "#FF0000"; // black line
var opacity = .5;
var lineWeight = 5;

var kmlFillColor = "7dff0000"; // half-opaque blue fill

$(window).unload(function() {
    GUnload();
});

$(document).ready(function() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(40.445069, -3.720508), 16);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());

        geocoder = new GClientGeocoder();
        map.openInfoWindow(map.getCenter(), "Crea las Zonas en el Mapa !!!");
    }

    $('#ir').click(function() {
        showAddress($("#address").val());
    });

    $('#eliminarPunto').click(function() {
        deleteLastPoint();
    });

    $('#limpiarMapa').click(function() {
        clearMap();
    });

    $('#guartdarZona').click(function() {
        guardarZona();
    });

    dialog_map = $('#mapa').dialog({
        autoOpen: false,
        draggable: false,
        resizable: true,
        bgiframe: true,
        height: 520,
        width: 825,
        modal: true,
        delay:100
    });

    dialog_coordenadasLista = $('#coordenadasLista').dialog({
        autoOpen: false,
        draggable: false,
        resizable: false,
        bgiframe: true,
        height: 50,
        width: 300,
        modal: true,
        delay:100,
        closeText:'',
        buttons : { "Salir": function() {
            $(this).dialog("close");
        }}
    });


    $('#new').click(function() {
        dialog_map.dialog('open');
    });


    $('#todos').click(function() {
        managerHelper.getAllZonas(function(zonas) {
            if (zonas != null) {
                for (var zona in zonas) {
                    dibujarZonasEnMapa(zonas[zona].id, true);
                }
            }
        });
    });

    $('a[name^="coordenadasLista"]').click(function() {

        var polyPuntos = new Array;
        $("#coordenadasLista").empty();
        managerHelper.getZonaById(this.id, function(zona) {
            if (zona != null) {
                for (var punto in zona.puntoList) {
                    polyPuntos.push(new GLatLng(zona.puntoList[punto].x, zona.puntoList[punto].y));
                }

                hacerGloboCoordenadas(zona, polyPuntos);
                $('#coordenadasLista').append(globoCoordenadas);
                $("#coordenadasLista").dialog("option", "height", (zona.puntoList.length * 23) + 100);
            }
            dialog_coordenadasLista.dialog('open');
        });
    });

    /*$('#row1').click(function() {
     var polyPoints = [
     new GLatLng(40.44460350616585, -3.7204331159591675),
     new GLatLng(40.44460758866772, -3.7202587723731995),
     new GLatLng(40.44497297158037, -3.7203043699264526),
     new GLatLng(40.44497093034055, -3.720473349094391),
     new GLatLng(40.44460350616585, -3.7204331159591675)
     ];
     dibujarPoligono(polyPoints);
     });*/


    activarEstilosTabla('zonas');

});

function dibujarZonasEnMapa(idZona, all) {


    if (!all) {
        GEvent.clearListeners(map, 'click');
        map.clearOverlays();
    }
    var polyPoints = new Array;
    managerHelper.getZonaById(idZona, function(zona) {
        if (zona != null) {
            for (var punto in zona.puntoList) {
                polyPoints.push(new GLatLng(zona.puntoList[punto].x, zona.puntoList[punto].y));
            }
            dibujarPoligono(polyPoints);
            hacerGloboCoordenadas(zona, polyPoints);
            map.addOverlay(crearMarcaPestanas(new GLatLng(totalLat / polyPoints.length, totalLon / polyPoints.length), ["Coordenadas"], [globoCoordenadas]));
            dialog_map.dialog('open');
        }
    });
}

function hacerGloboCoordenadas(zona, polyPoints) {

    globoCoordenadas = null;
    if (polyPoints == null) { // caso de la lista
        for (var punto in zonas.puntoList) {
            polyPoints.push(new GLatLng(punto.x, punto.y));
        }
    }
    var divInicio = "<h3>" + zona.nombre + "</h3><div id='coord'>" +
            "<table id='coordenadas' cellpadding='0' cellspacing='0'>" +
            "<thead><tr class=''><th>Latitud</th><th>Longitud</th></tr>" +
            "</thead><tbody id='coord'>";
    var coordenadas = "";
    for (var x = 0; x < polyPoints.length; x++) {

        if (x % 2 != 0)
            coordenadas += "<tr id='row" + x + "' class='odd'><td style='width: 10%'>" + polyPoints[x].y + "</td><td style='width: 10%'>" + polyPoints[x].x + "</td></tr>"
        else
            coordenadas += "<tr id='row" + x + "' class='even'><td style='width: 10%'>" + polyPoints[x].y + "</td><td style='width: 10%'>" + polyPoints[x].x + "</td></tr>"
        totalLat += polyPoints[x].y;
        totalLon += polyPoints[x].x;
    }
    var divFin = "</tbody></table></div>";
    globoCoordenadas = divInicio + coordenadas + divFin;
}

function crearMarcaPestanas(punto, arrayEtiquetas, arrayContenidos) {
    var marca = new GMarker(punto);
    var arrayPestanas = new Array();
    var anchuraPestanas = arrayEtiquetas.length * 90;
    for (i = 0; i < arrayEtiquetas.length; i++) {
        arrayPestanas[i] = new GInfoWindowTab(arrayEtiquetas[i], "<div>" + arrayContenidos[i] + "</div>");
    }
    GEvent.addListener(marca, "click", function() {
        marca.openInfoWindowTabsHtml(arrayPestanas);
    });
    return marca;
}

function dibujarPoligono(polyPoints) {

    var polyShape = new GPolygon(polyPoints, lineColor, lineWeight, opacity, fillColor, opacity);
    map.addOverlay(polyShape);
    map.setCenter(polyPoints[0], 18);
}

function dibujarZonas() {
    if ($("#dibujar").hasClass("botonNoDibuja")) {
        $("#dibujar").removeClass("botonNoDibuja");
        $("#dibujar").addClass("botonDibuja");
        GEvent.addListener(map, 'click', mapClick);

    } else {
        $("#dibujar").removeClass("botonDibuja");
        $("#dibujar").addClass("botonNoDibuja");
        GEvent.clearListeners(map, 'click')
    }

}


// mapClick - Handles the event of a user clicking anywhere on the map
// Adds a new point to the map and draws either a new line from the last point
// or a new polygon section depending on the drawing mode.


function mapClick(marker, clickedPoint) {
    //polygonMode = document.getElementById("drawMode_polygon").checked;
    polyPoints.push(clickedPoint);
    drawCoordinates();
}


// Clear current Map
function clearMap() {
    map.clearOverlays();
    polyShape = null;
    polyPoints = [];
    // logCoordinates();
    //document.getElementById("coords").innerHTML = "&lt;-- Click on the map to digitize!";
}


// Toggle from Polygon PolyLine mode

function toggleDrawMode() {
    map.clearOverlays();
    polyShape = null;
    polygonMode = document.getElementById("drawMode_polygon").checked;
    drawCoordinates();
}


// Clear current Map
function guardarZona() {

    if ($("#nombreZona").val() == '') {
        $("#errorNombre").append("El nombre de la zona es Obligatorio");
        map.openInfoWindow(map.getCenter(), "El nombre de la zona es Obligatorio");
    } else {
        if (polyPoints != null) {
            var firstPoint = polyPoints[0];
            mapClick(null, polyPoints[0]);


            var puntosArray = new Array();
            for (var i = 0; i < polyPoints.length; i++) {
                puntosArray[i] = {id:null, x:polyPoints[i].y, y:polyPoints[i].x};
            }

            var zona = {id:null, nombre:$("#nombreZona").val(),puntoList:puntosArray};

            managerHelper.salvarZona(zona, function(data) {
                if (data) {
                    window.open('<c:url value='/altaZonaSave.sms'/>', '_self');
                }
            });

        }
    }
}

// Delete last Point
// This function removes the last point from the Polyline/Polygon and redraws
// map.

function deleteLastPoint() {
    map.removeOverlay(polyShape);
    // pop last element of polypoint array
    polyPoints.pop();
    drawCoordinates();
}


// drawCoordinates
function drawCoordinates() {
    //Re-create Polyline/Polygon
    //GLog.write(polyPoints.length);
    //if (polygonMode) {
    polyShape = new GPolygon(polyPoints, lineColor, lineWeight, opacity, fillColor, opacity);


    //} else {
    //  polyShape = new GPolyline(polyPoints,lineColor,lineWeight,opacity);
    //}
    map.clearOverlays();
    map.addOverlay(polyShape);

    // Grab last point of polyPoints to add new marker
    var tmpPoint = polyPoints[polyPoints.length - 1];
    map.addOverlay(new GMarker(tmpPoint));
    logCoordinates();
}

// logCoordinates - prints out coordinates of global polyPoints array
//  This version only logs KML, but could be extended to log different types of output

function logCoordinates() {
    document.getElementById("point").innerHTML = document.getElementById("point").innerHTML + polyPoints[polyPoints.length - 1] + "<br/>";

}

function showAddress(address) {
    if ($("#address").val() == '') {
        address = "Paseo Juan XXIII, 328040 Madrid";
    }
    if (geocoder) {
        geocoder.getLatLng(address,
                          function(point) {
                              if (!point) {
                                  alert(" La Direccion " + address + " no es posible ubicarla en el mapa");
                              } else {
                                  geocoder.getLocations(address, function(addresses) {
                                      if (addresses.Status.code != 200) {
                                          alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
                                      }
                                      else {
                                          address = addresses.Placemark[0];
                                          var myHtml = address.address;
                                          map.openInfoWindow(point, myHtml);
                                      }
                                  });
                                  map.setCenter(point, 16);

                                  clearMap();
                              }
                          }
                );
    }
}


</script>
</head>
<html>
<body>

<form action="gestoZonas.jsp#">

    <div>
        <div id="status">
            <h3>Lista de Zonas</h3>
            <display:table cellspacing="0" cellpadding="0" name="list" id="zona" pagesize="20"
                           decorator="dyndecorator">
                <display:setProperty name="paging.banner.items_name">Zonas</display:setProperty>
                <display:setProperty name="paging.banner.item_name">Zona</display:setProperty>
                <display:column property="id" title="ID"/>
                <display:column property="nombre" title="Nombre"/>
                <display:column title="Coordenadas">
                    <a href="#" id="${zona.id}" name="coordenadasLista${zona.id}">Ver</a>
                </display:column>
                <display:column title="Accion">
                    <a href="#" onclick="dibujarZonasEnMapa(${zona.id}, false)">Ver en el Maps</a>
                </display:column>
                <display:column title="Accion">
                    <c:url value='bajaZona.sms' var="eliminarLink">
                        <c:param name="id">${zona.id}</c:param>
                    </c:url>
                    <a href="${eliminarLink}">Eliminar</a>
                </display:column>
            </display:table>
            <span id="point"></span>
        </div>
        <div class="clear"></div>
        <div class="botonesFormulario">
            <span id="boton"><input type="button" name="new" id="new" value="Crear Zona"/></span>
            <span id="botonTodas"><input type="button" name="todos" id="todos" value="Todas las Zona"/></span>
        </div>
    </div>

    <div id="mapa">
        <table>
            <tr>
                <td>
                    <h3>Datos de la nueva Zona</h3>
                    <label>Nombre</label>
                    <input type="text" size="40" id="nombreZona" name="nombreZona" value=""/>
                    <span id="errorNombre" class="error"></span>
                </td>
            </tr>
            <tr>
                <td>
                    <div id="map" style="width: 800px; height: 400px"></div>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="text" size="40" name="address" id="address" value=""/>
                    <input type="button" id="ir" value="Ir!"/>
                    <input type="button" id="eliminarPunto" value="Eliminar Ultimo Punto"/>
                    <input type="button" id="limpiarMapa" value="Limpiar Mapa"/>
                    <input type="button" id="guartdarZona" value="Guardar Zona"/>
                    <input type="button" id="dibujar" onclick="dibujarZonas();" value="Dibuajar Zonas"
                           class="botonNoDibuja"/>
                </td>
            </tr>
        </table>
    </div>
    <div id="coordenadasLista" class="capasCoordenadas">
    </div>


</form>

</body>
</html>